// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const  openid= wxContext.OPENID;
  const name=event.name;
  const phone=event.phone;
  const zone=event.zone;
  const address=event.address;
  const id=event.id;
  // const openid=event.openid;
  try {
    if(id){
           await db.collection('address').where({
             _id:id,
              }).update({
                data: {
                      name: name,
                      phone: phone, 
                      zone: zone,
                      address: address,
                }
              });
              return {
                 code:0,
                success: true,
                message: '保存成功'
              };
    }
    else{
      await db.collection('address').add({
        data:{
          name: name,
        phone: phone, 
        zone: zone,
        address: address,
        openId: openid
        }
      });
      return{
        code:0,
        message: '保存成功',
      }
    }
    
  } catch (error) {
    console.error('数据库操作失败:', error);
    return {
      code: -1,
      message: '操作失败'
    };
  }

}